﻿#region FileHeader
//////////////////////////////////////////////////////////////////////////////////
// Author:                          Hector Llanos
// Date:                            08.27.2010
// FileName:                        CNetworkSession.cs
// Reason:                          Get multiplayer in the game
//////////////////////////////////////////////////////////////////////////////////
#endregion

#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;

using Run_Game;
using Manager;
using Objects;
using Base;

#endregion

namespace Network
{
    public class CNetworkSession : Microsoft.Xna.Framework.Game
    {

        private NetworkSession networkSession;

        private PacketWriter packetWriter = new PacketWriter();
        private PacketReader packetReader = new PacketReader();

        private string errorMessage;

        const int maxGamers = 4;
        const int maxLocalGamers = 1;


        KeyboardState currentKeyboardState;
        GamePadState currentGamePadState;

        public CNetworkSession()
        {

            Game1.Instance.Components.Add(new GamerServicesComponent(this));

            // For XBOX Live
            Components.Add(new GamerServicesComponent(this));

            CreateSession();
        }
        public void Update(GameTime gametime)
        {
            //handle input

            if (networkSession != null)
                updateNetwork();
        }

        private void updateNetwork()
        {
            throw new NotImplementedException();
        }

        #region CREATE_JOIN_SESSION

        /// <summary>
        /// Starts hosting a new network session.
        /// </summary>
       private void CreateSession()
       {

            try
            {
                networkSession = NetworkSession.Create(NetworkSessionType.SystemLink, maxLocalGamers, maxGamers);
                
                HookSessionEvents();

                networkSession.AllowHostMigration = true;
            }
            catch (Exception e)
            {
                errorMessage = e.Message;
            }
        } 
        
       /// <summary>
       /// Joins an existing network session.
       /// </summary>
       void JoinSession()
       {

           //try
           //{
           // Search for sessions.
           using (AvailableNetworkSessionCollection availableSessions = NetworkSession.Find(NetworkSessionType.SystemLink, maxLocalGamers, null))
           {
               if (availableSessions.Count == 0)
               {
                   errorMessage = "No network sessions found.";
                   return;
               }

               // Join the first session we found.
               networkSession = NetworkSession.Join(availableSessions[0]);

               HookSessionEvents();
           }
           //}
           //catch (Exception e)
           //{
           //    errorMessage = e.Message;
           //}
       }

       /// <summary>
       /// This event handler will be called whenever a new gamer joins the session.
       /// We use it to allocate a Tank object, and associate it with the new gamer.
       /// </summary>
       void GamerJoinedEventHandler(object sender, GamerJoinedEventArgs e)
       {
           int gamerIndex = networkSession.AllGamers.IndexOf(e.Gamer);

           CPlayer1 player = (CPlayer1)ObjectFactory<string, CBase>.Instance.CreateObject("Player1");
           try
           {
               // pl.GamerImage = e.Gamer.GetProfile().GetGamerPicture().;
               //player.Gamertag = e.Gamer.Gamertag;
           }
           catch (Exception ex)
           {
              // pl.GamerImage = Content.Load<Texture2D>("NonLivePlayer");
               //pl.Gamertag = "Non Live Player " + gamerIndex;
           }
           e.Gamer.Tag = player;

       }


       /// <summary>
       /// Event handler notifies us when the network session has ended.
       /// </summary>
       void SessionEndedEventHandler(object sender, NetworkSessionEndedEventArgs e)
       {
           errorMessage = e.EndReason.ToString();

           networkSession.Dispose();
           networkSession = null;
       }

       /// <summary>
       /// After creating or joining a network session, we must subscribe to
       /// some events so we will be notified when the session changes state.
       /// </summary>
       void HookSessionEvents()
       {
           networkSession.GamerJoined += GamerJoinedEventHandler;
           networkSession.SessionEnded += SessionEndedEventHandler;
       }

        #endregion
    }
}
